package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    //用户下单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("用户下单信息：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 按照时间提供最新的订单
     * @return
     */
    @GetMapping("/userPage")
    public  R userPage(Integer page, Integer pageSize, HttpSession session){
        //1.通过session获取用户id
        Long empID = (Long) session.getAttribute("empID");
        //2.根据id获取用户的订单信息
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(empID!=null,Orders::getUserId,empID);
        wrapper.orderByDesc(Orders::getOrderTime);
        List<Orders> order =  orderService.list(wrapper);


        //3.设置分页信息
        Page<Orders> ordersPage = new Page<Orders>(page,pageSize);
        Page<Orders> page1 = orderService.page(ordersPage, wrapper);



        return R.success(page1);
    }

    /**
     * 分页查询+订单号模糊查询
     * @return
     */
    @GetMapping("/page")
    public R pageAndMoHu(@RequestParam Integer page, Integer pageSize, Integer number,
                         HttpSession session, @DateTimeFormat String startTime, @DateTimeFormat String endTime ){
        //获取分页
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //通过seeion获取对象
        Long userID = (Long) session.getAttribute("empID");

        //通过id获取对象
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(userID!=null,Orders::getUserId,userID);
        //创建时间大于等于startTime
        //创建时间小于等于endTime
        wrapper.ge(startTime!=null,Orders::getOrderTime,startTime).le(endTime!=null,Orders::getOrderTime,endTime);
        wrapper.eq(number!=null,Orders::getNumber,number);

        orderService.page(ordersPage, wrapper);
//        List<Orders> list = orderService.list(wrapper);


        return R.success(ordersPage);
    }
}
